import heapq
import collections
class Solution:
    def longestEqualSubarray(self, nums, k: int) -> int:
        def cal(val):
            d = collections.defaultdict(int)
            for i in range(min(n, val + k)):
                d[nums[i]] += 1
            st = [[ - num, key] for key, num in d.items()]
            st.sort()
            if - st[0][0] >= val:
                return True
            for i in range(val + k, n):
                d[nums[i]] += 1
                d[nums[i - val - k]] -= 1
                heapq.heappush(st, [ - d[nums[i]], nums[i]])
                while - st[0][0] != d[st[0][1]]:
                    heapq.heappop(st)
                if - st[0][0] >= val:
                    return True
            return False
        n = len(nums)
        left = 1
        right = n
        print(cal(3))
        while left < right:
            mid = (left + right + 1) // 2
            if cal(mid):
                left = mid
            else:
                right = mid - 1
        return left

data = Solution()
nums = [1,3,2,3,1,3]
k = 3
print(data.longestEqualSubarray(nums, k))